package com.fau.cm.action.index;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

import com.fau.cm.action.PublicAction;
import com.fau.cm.entity.MedicalAdmin;
import com.fau.cm.util.SystemConfig;
import com.opensymphony.xwork2.ModelDriven;

/**
 * @desc 业务系统与软交换交互Action
 * @author kangyj
 * @datetime 2014年12月24日,上午12:20:29
 */
@Controller
@Scope("prototype")
@ParentPackage("default")
@Namespace("/")
public class AlternatelyAction extends PublicAction implements ModelDriven<MedicalAlternately>{

	private static final long serialVersionUID = 3397229732155311020L;
	
	private MedicalAlternately alternately = new MedicalAlternately();

	/**
	 * @desc 来电弹屏
	 * @return
	 * @author kangyj
	 * @datetime 2014年12月23日,下午11:13:04
	 */
	@Action(value = "alternately_play_screen", results = {@Result(location = "alternately_play_screen.jsp")})
	public String playScreen() {
		return SUCCESS;
	}
	
	/**
	 * @desc 绑定分机
	 * @return
	 * @author kangyj
	 * @datetime 2014年12月24日,上午11:54:07
	 */
	@Action(value = "alternately_login_ext")
	public String loginExt() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		this.baseAllService.getAlternatelyManagerService().loginExt(alternately.getUserName(), alternately.getExtension(), alternately.getQueue());
		map.put("success", true);
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 离席
	 * @return
	 * @author kangyj
	 * @datetime 2015年2月4日,上午9:33:31
	 */
	@Action(value = "alternately_loginout_ext")
	public String loginOutExt() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		this.baseAllService.getAlternatelyManagerService().loginOutExt(alternately.getUserName(), alternately.getExtension(), alternately.getQueue());
		map.put("success", true);
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 弹屏后加载页面信息
	 * @return
	 * @author kangyj
	 * @datetime 2015年1月11日,下午3:08:40
	 */
	@Action(value = "alternately_save_call")
	public String loadInfo() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		List<Object> callList = this.baseAllService.getCallManagerService().incomfindCall(alternately.getDid(), alternately.getPhoneNum());
		if(callList.size() == 1) {	
			map.put("info", "fail");
		} else if(callList.size() > 1) {		// 任务存在,更新任务类别、次数
			String callIdAndStatus = this.baseAllService.getCallManagerService().incomUpdateCall(callList, alternately);
			map.put("info", "have");
			map.put("cId", callIdAndStatus.substring(0, callIdAndStatus.lastIndexOf("|")));
			map.put("callStatus", callIdAndStatus.substring(callIdAndStatus.lastIndexOf("|") + 1));
		} else {								// 任务不存在，创建任务
			String callIdAndStatus = this.baseAllService.getCallManagerService().incomsaveCall(admin, alternately);
			if(StringUtils.isNotBlank(callIdAndStatus)) {
				map.put("info", "no");
				map.put("cId", callIdAndStatus.substring(callIdAndStatus.lastIndexOf("|") + 1));
				map.put("callStatus", callIdAndStatus.subSequence(0, callIdAndStatus.lastIndexOf("|")));
			} else {
				map.put("info", "fail");
			}
		}
		if(!SystemConfig.INCOMING_POPUP_TYPE.equals(alternately.getPopupType())) {
			this.baseAllService.getCallManagerService().saveCallCaller(alternately.getPhoneNum(), admin);
		}
		formatJSON(response, map);
		return null;
	}

	/**
	 * @desc 忙转修改任务处理者
	 * @return
	 * @author kangyj
	 * @datetime 2015年2月6日,下午4:42:17
	 */
	@Action(value = "alternately_busy_turn")
	public String busyTurn() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(alternately.getCallId()) && StringUtils.isNotBlank(alternately.getExtension())) {
			this.baseAllService.getCallManagerService().busyTurn(alternately.getCallId(), alternately.getExtension());
			map.put("success", true);
		} else {
			map.put("success", false);
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 根据工号获取分机号和队列号
	 * @return
	 * @author kangyj
	 * @datetime 2015年1月14日,下午8:06:05
	 */
	@Action(value = "alternately_find_ext_queue")
	public String findQueue() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String extQueue = this.baseAllService.getAlternatelyManagerService().findExtQueue(admin);
		if(StringUtils.isNotBlank(extQueue)) {
			String[] extQueues = extQueue.split("\\|");
			map.put("extension", extQueues[0]);
			map.put("queue", extQueues[1]);
			map.put("success", true);
		} else {
			map.put("success", false);
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 查看所有分机页面初始化
	 * @return
	 * @author kangyj
	 * @datetime 2015年1月27日,下午2:54:10
	 */
	@Action(value = "alternately_extension_init", results = {@Result(location = "alternately_extension_init.jsp")})
	public String extensionInit() {
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String extension = this.baseAllService.getAlternatelyManagerService().findExtension(admin.getEnterpriseId());
		alternately.setExtension(extension);
		return SUCCESS;
	}
	
	/**
	 * @desc 跳转到分机管理页
	 * @return
	 * @author kangyj
	 * @datetime 2015年1月29日,下午3:16:30
	 */
	@Action(value = "alternately_extension_manage", results = {@Result(location = "alternately_extension_manage.jsp")})
	public String extensionManage() {
		alternately.setExtension(alternately.getExtension());
		return SUCCESS;
	}
	
	/**
	 * @desc 跳转到队列管理页
	 * @return
	 * @author kangyj
	 * @datetime 2015年1月29日,下午3:17:28
	 */
	@Action(value = "alternately_queue_manage", results = {@Result(location = "alternately_queue_manage.jsp")})
	public String queueManage() {
		return SUCCESS;
	}
	
	/**
	 * @desc 查询分机通话信息（呼入数/时长、呼出数/时长）
	 * @return
	 * @author kangyj
	 * @datetime 2015年1月29日,上午11:36:47
	 */
	@Action(value = "alternately_extension_call")
	public String extensionCallView() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		list = this.baseAllService.getAlternatelyManagerService().getExtensionCall(alternately.getExtension());
		map.put("callerCount", list.get(0));
		map.put("callLength", list.get(1));
		map.put("exhale", list.get(2));
		map.put("callDuration", list.get(3));
		map.put("jobNum", list.get(4));
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 查询没有加入到当前队列的分机号
	 * @return
	 * @author kangyj
	 * @datetime 2015年1月30日,下午2:26:23
	 */
	@Action(value = "alternately_no_extension")
	public String findNOExtension() {
		HttpServletResponse response = ServletActionContext.getResponse();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		list = this.baseAllService.getAlternatelyManagerService().findNoExtension(alternately.getQueue(), admin.getEnterpriseId());
		formatJSON(response, list);
		return null;
	}
	
	/**
	 * @desc 更新分机队列
	 * @return
	 * @author kangyj
	 * @datetime 2015年1月30日,下午4:28:48
	 */
	@Action(value = "alternately_add_extension")
	public String addExtension() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(alternately.getExtension()) && StringUtils.isNotBlank(alternately.getQueue())) {
			this.baseAllService.getAlternatelyManagerService().addExtension(alternately.getExtension(), alternately.getQueue());
			map.put("success", true);
		} else {
			map.put("success", false);
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 从队列中移除分机
	 * @return
	 * @author kangyj
	 * @datetime 2015年2月1日,下午8:44:30
	 */
	@Action(value = "alternately_remove_extension")
	public String removeExtension() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(alternately.getExtension()) && StringUtils.isNotBlank(alternately.getQueue())) {
			this.baseAllService.getAlternatelyManagerService().removeExtension(alternately.getExtension(), alternately.getQueue());
			map.put("success", true);
		} else {
			map.put("success", false);
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 会议管理页面初始化
	 * @return
	 * @author kangyj
	 * @datetime 2015年2月2日,上午10:05:43
	 */
	@Action(value = "alternately_meeting_init", results = {@Result(location = "alternately_meeting_init.jsp")})
	public String meetingInit() {
		return SUCCESS;
	}
	
	/**
	 * @desc 查询当前用户分机
	 * @return
	 * @author kangyj
	 * @datetime 2015年2月3日,上午10:43:03
	 */
	@Action(value = "alternately_cur_extension")
	public String findCurExtension() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String phoneNum = this.baseAllService.getAlternatelyManagerService().findCurExtension(admin.getId());
		map.put("phoneNum", phoneNum);
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 查询所有队列
	 * @return
	 * @author kangyj
	 * @datetime 2015年2月3日,上午11:40:57
	 */
	@Action(value = "alternately_find_queue")
	public String findAllQueue() {
		HttpServletResponse response = ServletActionContext.getResponse();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		list = this.baseAllService.getAlternatelyManagerService().findAllQueue(admin);
		formatJSON(response, list);
		return null;
	}
	
	/**
	 * @desc 查询分机是否已被其他用户登录
	 * @return
	 * @author kangyj
	 * @datetime 2015年3月7日,下午6:50:33
	 */
	@Action(value = "alternately_find_Extension_online")
	public String findExtensionOnline() {
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		MedicalAdmin admin = this.baseAllService.getAlternatelyManagerService().findExtensionOnline(alternately.getExtension());
		if(null != admin) {
			map.put("success", false);
		} else {
			map.put("success", true);
		}
		formatJSON(response, map);
		return null;
	}

	@Override
	public MedicalAlternately getModel() {
		return alternately;
	}

}
